package Server;

import java.io.*;
import java.net.*;

/*
 * Message Formats:
 * Type 0 : Get Servers Public Key.
 *  2 Bits : Type 
 */

/**
 * The RequestParser class is responsible
 * for serving a clients request.
 * @author Jithesh, Nevil, Saurav, Sajin ,Vineeth
 */
public class RequestParser implements Runnable {

	/**
	 * The constructor.
	 * @param clientSock The TCP Socket to the client
	 * which is to be served.
	 */
	public RequestParser(Socket clientSock) {
		clientSocket = clientSock;
		parseRequest = new Thread(this,"Parse_Request");
		parseRequest.start();
	}

	@Override
	public void run() {
		try {
			DataInputStream fromClient = new DataInputStream( clientSocket.getInputStream() );
			DataOutputStream toClient = new DataOutputStream( clientSocket.getOutputStream() );

			byte[] request = new byte[1024];
			fromClient.read(request);

			// Extract the type of the message from first 4 bytes.
			// To do that Mask with 1111 0000 - decimal 240 - to the input.
			// Now we get the higher 4 bits and 4 right unsigned shifts will
			// give the value of Type as integer.
			
			int type = request[0] & 240;
			type = type >>> 4; // 4 unsigned left shifts.
			switch( type ) {
				case 0:
					String publicKey;
					publicKey = ServerConfiguration.getPublicKey();
					toClient.write( publicKey.getBytes() , 0 , publicKey.getBytes().length );
					break;
				default:
					System.err.println( "Error Occured " );
					break;
			}
		} catch ( Exception e) {
			System.err.println("Error Occured " + e.getMessage() );
		}
	}

	protected Thread parseRequest;
	protected Socket clientSocket;
}
